package com.pw.canbuslogger.view.grid;

import java.awt.Color;
import java.awt.Component;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

import com.tuamotu.commons.dataset.Dataset;

public class CANBusGridTableCellRender extends DefaultTableCellRenderer {

    private static final long serialVersionUID = 2947959508028568839L;
    private final SimpleDateFormat DATE_FORMAT;

    public CANBusGridTableCellRender() {
        this.DATE_FORMAT = new SimpleDateFormat("mm:ss:SSS");
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Component cmp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        cmp.setBackground(Color.WHITE);

        CANBusDatasetTableModel model = (CANBusDatasetTableModel) table.getModel();
        Dataset<Object[]> dataset = model.getDataset();
        Calendar lastChange = dataset.getValue(row, model.LAST_FIELD, model.datasetIndex);

        long age = Calendar.getInstance().getTimeInMillis() - lastChange.getTimeInMillis();

        if (age < 1000) {
            cmp.setBackground(Color.YELLOW);
        }

        if (model.getColumnName(column).equals(model.LAST_FIELD.getDescription())) {
            String fmt = DATE_FORMAT.format(lastChange.getTime());
            this.setText(fmt);
            cmp.setBackground(Color.GRAY);
        } else if (model.getColumnName(column).equals(model.COUNT_FIELD.getDescription())) {
            cmp.setBackground(Color.GRAY);
        }

        if (isSelected) {
            cmp.setBackground(Color.BLUE);
        }

        return cmp;
    }

}
